#!/bin/bash

# Variable sanitazing function - at least we try...
function sanitize()
{
        echo "${*//[^a-zA-Z0-9 .,;:&#-]/_}"
}


if [ "$1" == "ul_ov" ]
then
	spellsite="http://www.undeadspells.com/overlords/showspells.php"
	website="www.undeadlive.com"
	own_id=223980302
	game=undead
	serverid=_undead_j2
	old_code_file=oldspells
	ok="Success:"
	nok="Failure:"
	rotation_day=0
elif [ "$1" == "eow" ]
then
	spellsite="http://www.undeadspells.com/eow/showspells.php"
	website="www.enginesofwar.com"
	own_id=134463201
	game=army
	serverid=army_1
	old_code_file=oldkeys
	ok="Hoo Rah:"
	nok="Negative:"
	day=$(date -u +"%-d")
	rotation_day=$(( $day % 3 ))
else
	echo "unknown parameter"
	exit
fi

echo "website is : $website"
echo "game is : $game"
echo "serverid : $serverid"

[ ! -f "$old_code_file" ] && touch "$old_code_file"

if [ -f /home/sioban/.mozilla/firefox-3.5/2gufwxr0.default/cookies.sqlite ] 
then
	/bin/cp /home/sioban/.mozilla/firefox-3.5/2gufwxr0.default/cookies.sqlite .
	session=$(sqlite3 -line cookies.sqlite 'select value from moz_cookies where name = "_'${game}'_session" order by expiry DESC;' | head -1 | sed "s/value = //")
else
	session="$(cat cookie_$game)"
fi
echo "found session : $session"

#get spell list
spellfile=spellfile
curl -s $spellsite | sed "s@</tr>@</tr>\n@g" | sed 's@^<tr><td>\([0-9]*\)</td><td><img src="[^"]*" alt="[^"]*"></td><td>\([^<]*\)</td><td>\([^<]*\)</td><td>\([^<]*\)</td><td>\([^<]*\)</td><td>.*@\1,\2,\3,\4,\5@p;d' > $spellfile

hour="$(date -u +"%-H")"

if [[ $hour -ge 12 ]] 
then
	valid_since=$(( $hour - 12 + $rotation_day * 24 ))
else
	valid_since=$(( $hour + 12 + $rotation_day * 24 ))
fi

echo "Code valid since ${valid_since}h"

if [[ $hour -ge 12 && $rotation_day -eq 0 ]]
then
	back=$(( $hour - 7 ))
else
	back=$(( $hour - 7 + $rotation_day * 24 ))
fi

today_reset="$(date -u --date "$back hours ago" +"%Y-%0m-%d") 05:"
echo "looking for spells since $today_reset"

newdayline="$(grep -n "$today_reset" "$spellfile"|head -1|cut -d":" -f1)"

[[ ! "$newdayline" ]] && newdayline=1

spells_to_be_added=spells_to_be_added
tail -n +$newdayline "$spellfile" > $spells_to_be_added

own_code="$(grep $own_id "$spells_to_be_added"|head -1|cut -d"," -f5)"

if [ ! "$own_code" ]
then
	echo "You must add your own spell with your courtcode for the day on the spellsheet" 
	exit
fi

echo "our code is : $own_id"
echo "our spell code is : $own_code"

# find highest item id available
           item_id="$(curl -s -H "Host: $website" \
                                -H "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.2) Gecko/20090803 Ubuntu/9.04 (jaunty) Shiretoko/3.5.2" \
                                -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" \
                                -H "Accept-Language: en-us,en;q=0.5" \
                                -H "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7" \
                                -H "Keep-Alive: 300" \
                                -H "Connection: keep-alive" \
                                -H "Cookie: _${game}_session=$session; SERVERID=$serverid" \
			http://$website/viral | sed "s/.*ASJS.Viral.register_item(.*\"id\": \([0-9]*\).*/\1/p;d"|head -1)"

echo "Selecting item_id : $item_id"

OLDIFS=$IFS
IFS="
"

good_keys=0
> bad_key_code
> bad_court_code
> bad_species_code

for line in $(cat "$spells_to_be_added" | grep "^[0-9 :-]*," | egrep -v "$own_id")
do
	line_number="$(echo "$line"|cut -d"," -f1)"
	name="$(echo "$line"|cut -d"," -f3)"
	name_cleaned="$(sanitize "$name")"
	code="$(echo "$line"|cut -d"," -f4|sed "s/[^0-9]*//g"|sed "s/[ -]*//g" | cut -c1-9)"
	key_code="$(echo "$line"|cut -d"," -f5|sed "s/[^A-Za-z]*//g"|cut -c1-4)"

	if [ ! ${#code} -eq 9 ]
	then
		code=""
	fi
	
	if [ ${#key_code} -eq 4 -a ! "$(grep "$name_cleaned,$code,$key_code" "$old_code_file")" ] 
	then
				# -H "Accept-Encoding: gzip,deflate" \
		return="$(curl -s -d "viral_item_id=${item_id}&friend_code=${key_code}&family_code=${code}&own_code=$own_code" \
				-H "Host: $website" \
				-H "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.2) Gecko/20090803 Ubuntu/9.04 (jaunty) Shiretoko/3.5.2" \
				-H "Accept: text/javascript, text/html, application/xml, text/xml, */*" \
				-H "Accept-Language: en-us,en;q=0.5" \
				-H "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7" \
				-H "Keep-Alive: 300" \
				-H "Connection: keep-alive" \
				-H "X-Requested-With: XMLHttpRequest" \
				-H "X-Prototype-Version: 1.6.0.3" \
				-H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
				-H "Referer: http://$website/viral" \
				-H "Cookie: _${game}_session=$session; SERVERID=${serverid}" \
				-H "Pragma: no-cache" \
				-H "Cache-Control: no-cache" \
			http://$website/viral/exchange )"

		box="$(echo $return| sed "s@</div>@</div>\n@g"| sed "s/<span [^>]*>//g" | sed "s@</span>@@g" | sed "s@.*-box\\\\\">\([^<]*\)<.*@\1@p;d")"

	        if [[ "$return" =~ "relogin" ]]
       	        then
                      	echo "you must reset the session cookie"
                       	exit -1
		elif [[ ! "$box" ]]
		then
			echo "Unknown reply, check out !"
			exit
		else
			echo "($line_number) $name + $code + $key_code = $box" | tee -a spell_messages
		
			if [[ "$box" =~ "$ok" ]]
			then
				good_keys=$(( $good_keys + 1 ))
				echo "$name_cleaned,$code,$key_code" >> "$old_code_file"
			elif [[ ! "$box" =~ "$nok" ]]
			then
				echo "Did not understood the reply :!!!!"
				cat tt
				exit
			else
				[[ "$box" =~ "is not an active" ]] && echo "($line_number) $name + $code + $key_code = $box" >> bad_key_code
				[[ "$box" =~ "same species" ]] && echo "($line_number) $name + $code + $key_code = $box" >> bad_species_code
				[[ "$box" =~ "Could not find" ]] && echo "($line_number) $name + $code + $key_code = $box" >> bad_court_code
			fi
		fi
	fi
done

echo "Done !"
echo ""
echo "Added $good_keys !!"

n_bkc="$(wc -l bad_key_code|cut -d" " -f1)"
n_bsc="$(wc -l bad_species_code|cut -d" " -f1)"
n_bcc="$(wc -l bad_court_code|cut -d" " -f1)"

if [[ "$n_bkc" -gt 1 ]]
then
	echo
	echo "found $n_bkc bad key codes: "
	cat bad_key_code
fi

if [[ "$n_bsc" -gt 1 ]]
then
	echo
	echo "found $n_bsc bad species codes: "
	cat bad_species_code
fi

if [[ "$n_bcc" -gt 1 ]]
then
	echo
	echo "found $n_bcc bad court codes: "
	cat bad_court_code
fi
